package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.geoaimavlink_android.R
import com.geoai.mavlink.geoainet.base.constant.GEOAIConstant
import kotlinx.android.synthetic.main.frag_version.tv_version
import java.lang.StringBuilder

class VersionFragment: BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_version, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSDK()
    }

    private fun initSDK() {
        msdkInfoVm.msdkInfo.observe(viewLifecycleOwner) {
            if (it.isAircraftConnected.not()) tv_version?.text = ""
            else {
                val sb = StringBuilder()
                getProduct()?.systemManager?.componentVersionInfo?.forEach { (id, versionInfo) ->
                    sb.append("id: $id")
                        .append(",  comp: ${analyzeComponentType(id!!.toInt())}")
                        .append(",  hw: ${versionInfo.hwVersionCode}")
                        .append(",  sw: ${versionInfo.swVersionCode}")
                        .append(",  version: ${analyzeSoftWareVersionInfo(versionInfo.swVersionCode)}")
                        .append("\r\n")
                }
                tv_version?.text = sb.toString()
            }
        }
    }

    private fun analyzeSoftWareVersionInfo(s: Long): String {
        val major = (s shr 24).toInt()
        val minor = (s shr 16 and 0xff).toInt()
        val patch = (s shr 8 and 0xff).toInt()
        val type = (s and 0xff).toInt()
        return "$major.$minor.$patch.$type"
    }

    private fun analyzeComponentType(id: Int): String {
        return when(id) {
            GEOAIConstant.MAVLINK_SYS_COMP_TYPE_FC -> "FC"
            GEOAIConstant.MAVLINK_SYS_COMP_TYPE_CREST -> "CREST"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_GIMBAL -> "GIMBAL"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_CAMERA -> "CAMERA"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_BATTERY -> "BATTERY"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_RTK -> "RTK"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_ECS1 -> "ECS1"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_ECS2 -> "ECS2"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_ECS3 -> "ECS3"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_ECS4 -> "ECS4"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_PARACHUTE -> "PARACHUTE"
            GEOAIConstant.MAVLINK_SYS_HEARTBEAT_TYPE_PAIR_AIRLINK -> "PAIR_AIRLINK"
            else -> id.toString()
        }
    }
}